package com.jinhuhang.u2.myselfmodule.engine.recharge;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fuiou.mobile.FyPay;
import com.fuiou.mobile.FyPayCallBack;
import com.fuiou.mobile.bean.MchantMsgBean;
import com.fuiou.mobile.util.AppConfig;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.BankBranch;
import com.jinhuhang.u2.entity.RechargeBean;
import com.jinhuhang.u2.entity.UserBean;
import com.jinhuhang.u2.invertmodule.ResultActivity;
import com.jinhuhang.u2.myselfmodule.engine.bank.BankActivity;
import com.jinhuhang.u2.util.RSAEncryptor;
import com.jinhuhang.u2.util.U2DialogUtil;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapper;
import com.jinhuhang.u2.util.http.HttpWrapperList;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;

/**
 * Created by OnionMac on 17/9/21.
 */

public class RechargeActivity extends ZSimpleBaseActivity implements RechargeContract.View{

    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.recharge_balance)
    TextView mRechargeBalance;
    @Bind(R.id.recharge_money)
    TextView mRechargeMoney;
    @Bind(R.id.recharge_edt)
    EditText mRechargeEdt;
    @Bind(R.id.btn_recharge)
    AppCompatButton mBtnRecharge;
    @Bind(R.id.recharge_bank_icon)
    ImageView mRechargeBankIcon;
    @Bind(R.id.recharge_bank_card)
    TextView mRechargeBankCard;
    @Bind(R.id.recharge_all)
    RelativeLayout mRechargeAll;
    @Bind(R.id.recharge_arraw)
    ImageView mRechargeArraw;

    private boolean goBank = false;
    private RechargeContract.Presenter mPresenter;
    private String orderNo;

    @Override
    protected void initView() {
        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText(R.string.recharge);

        UserBean user = getUser();
        if(user != null){
            String status = user.getStatus();
            if("1".equals(status)){
                mRechargeArraw.setVisibility(View.GONE);
            }else{
                goBank = true;
                mRechargeArraw.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        String useMoney = intent.getStringExtra("userMoney");

        mRechargeBalance.setText(useMoney);

        UserBean user = getUser();
        String cardNo = RSAEncryptor.androidDecryt(user.getCardNo());
        mRechargeBankCard.setText(UtilsCollection.connectString("(尾号",cardNo.substring(cardNo.length()-4,cardNo.length()),")"));
        BankBranch bankBranch = UtilsCollection.getBankBranch(user.getBankId());
        mRechargeBankIcon.setImageResource(bankBranch.getBankIcon());
    }
    UserBean singleData;
    @Override
    public void onAutoLoginResult(HttpWrapperList<UserBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
             singleData = o.getSingleData();
            UserBean oldUser = getUser();
            singleData.setUserName(oldUser.getUserName());
            singleData.setLoginPwd(oldUser.getLoginPwd());
            setUser(singleData);
            String bankCardNo =  RSAEncryptor.androidDecryt(singleData.getCardNo());
            String money = mRechargeEdt.getText().toString();
            Map<String,String> map = new HashMap<>();
            map.put("userId",singleData.getUserId());
            map.put("source","3");
            map.put("purchaseMoney",money);
            map.put("acc_no",bankCardNo);
            map.put("pay_code",singleData.getBankId());
            map.put("mobile",singleData.getUserName());
            mPresenter.recharge(map);
        }else{
            mBtnRecharge.setClickable(true);
            showDialog(o.getInfo());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        dissDialog();
    }

    @Override
    public void onRechargeResult(HttpWrapper<RechargeBean> o) {
        if(Constant.SUCCESS_CODE == o.code){
            toRecharge(o.getData());
        }else if("999".equals(o.code)){
            dissDialog();
            String retMsg = "银行卡号与所选银行不匹配，请重新绑卡!" ;
            Toast toast = U2DialogUtil.makeToast(this, retMsg);
            toast.show();
        }else{
            dissDialog();
            String retMsg = "对不起，充值失败" ;
            Toast toast = U2DialogUtil.makeToast(this, retMsg);
            toast.show();
        }
    }
    //String appPrimaryKey="gjs3off3o6q9pdpv1m8aevr22cfzpt2h";
    //测试密钥
    String appPrimaryKey="5old71wihg2tqjug9kkpxnhx9hiujoqj";
    private void toRecharge(RechargeBean data) {
        Bundle bundle =new Bundle();
        bundle.putString(AppConfig.MCHNT_CD, data.getMchntcd());  //MchNtCd.getText().toString();
        bundle.putString(AppConfig.MCHNT_AMT,data.getAmt());  // Amt.getText().toString();
        bundle.putString(AppConfig.MCHNT_BACK_URL,data.getBackurl() ); //"http://www-1.fuiou.com:18670/mobile_pay/update/receive.pay"
        bundle.putString(AppConfig.MCHNT_BANK_NUMBER,data.getBankcard());// BankCard.getText().toString()
        bundle.putString(AppConfig.MCHNT_ORDER_ID,data.getMchntorderid()); // MchntOrdId.getText().toString()
        bundle.putString(AppConfig.MCHNT_USER_IDCARD_TYPE,data.getIdtype());//IdType.getText().toString()
        bundle.putString(AppConfig.MCHNT_USER_ID,data.getUserid());//UserId.getText().toString()
        bundle.putString(AppConfig.MCHNT_USER_IDNU,data.getIdno());//IdNo.getText().toString()
        bundle.putString(AppConfig.MCHNT_USER_NAME,data.getName());//Name.getText().toString()
        bundle.putString(AppConfig.MCHNT_SING_KEY,data.getSign()); //Sing
        bundle.putString(AppConfig.MCHNT_SDK_SIGNTP,data.getSigntp());//"MD5"
        bundle.putString(AppConfig.MCHNT_SDK_TYPE,data.getType());
        bundle.putString(AppConfig.MCHNT_SDK_VERSION,data.getVersion());
        FyPay.setDev(false);
        FyPay.init(this);

        MchantMsgBean bean = new MchantMsgBean();
        bean.setOrderId(data.getMchntorderid());
        bean.setKey(appPrimaryKey);
        bean.setMchntCd(data.getMchntcd());//设置商户号
        bean.setAmt(data.getAmt());
        bean.setUserId(data.getUserid());
        bean.setCardNo(data.getBankcard());
        bean.setIDcardType(data.getIdtype());
        bean.setIDNo(data.getIdno());
        bean.setUserName(data.getName());
        bean.setBackUrl(data.getBackurl());
        bean.setPayType("mobilePay");
//        bean.setSdkVersion(data.getVersion());
//        bean.setSdkSignTp(data.getSigntp());
//        bean.setSdkType(data.getType());
//        bean.setSignKey(data.getSign());
        Log.i("myText", data.toString());
        orderNo = data.getMchntorderid();
        int result = FyPay.pay(this, bean, new FyPayCallBack() {

            @Override
            public void onPayComplete(String arg0, String arg1, Bundle arg2) {
                fail();
            }

            @Override
            public void onPayBackMessage(String data) {
//				// TODO Auto-generated method stub
                Log.i("myText", "----------extra:"+data.toString());
                try {
                    String result= data.substring(data.indexOf("<RESPONSECODE>"), data.lastIndexOf("</RESPONSECODE>"));
                    result=result.replace("<RESPONSECODE>","").trim();
                    if("0000".equals(result)){
                        /**
                         * 成功 更新银行卡的状态
                         */
                        UserBean user = getUser();
                        user.setStatus("1");
                        setUser(user);
                        mBtnRecharge.setClickable(true);
                        Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
                        intent.putExtra(ResultActivity.typestr,Constant.recharge_success);
                        intent.putExtra("rechargeMoney",mRechargeEdt.getText().toString());
                        startActivity(intent);
                    }else{
                        //错误
                        fail();
                    }
                } catch (Exception e) {
                    //TODO错误
                    fail();
                }
            }
        });
        if (result==0){
            dissDialog();
        }
    }

    /**
     * 充值失败
     */
    private void fail(){
        dissDialog();
        mBtnRecharge.setClickable(true);
        mPresenter.rechargeFail(singleData.getUserId(),orderNo);
        Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
        intent.putExtra(ResultActivity.typestr,Constant.recharge_fail);
        startActivity(intent);
    }

    @Override
    protected void initListener() {
        mBtnRecharge.setOnClickListener(v -> {
            String money = mRechargeEdt.getText().toString();
            if(TextUtils.isEmpty(money)){
                UtilsCollection.getSingleDialog(this,"温馨提示","请输入充值金额","确定",null).show();
                return;
            }

            if(!UtilsCollection.isNumber(money)){
                UtilsCollection.getSingleDialog(this,"温馨提示","请输入正确的金额","确定",null).show();
                return;
            }

            UserBean user = getUser();
            mPresenter.autoLogin(user.getUserId(),user.getUserName());
            mBtnRecharge.setClickable(false);
        });

        mRechargeAll.setOnClickListener(v -> {
            if(goBank)
            startActivity(new Intent(this, BankActivity.class));
        });
    }

    @Override
    protected void attachPre() {
        mPresenter = new RechargePresenter(this,getCompositeSubscription());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recharge;
    }

}
